import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import defaultConfig from '@/config/default_config'
import type { Pokemon, PokemonGlobaData } from '@/types/pokemon'

export interface PokemonMap {
  [key: string]: Pokemon
}

// 为window对象添加类型声明
declare global {
  interface Window {
    $poketmon: PokemonGlobaData
  }
}

// 创建全局宝可梦数据对象
export const GlobalPokemonData: PokemonGlobaData = {
  data: {},
  dataArr: [],
  length: 0,
  getDataById: (id: string) => GlobalPokemonData.data[id],
}

// 将全局变量添加到window对象，使其在全局可访问
if (typeof window !== 'undefined') {
  ;(window as any).$poketmon = GlobalPokemonData
}

export const usePokemonAllStore = defineStore('pokemonAll', () => {
  const pokemonMap = ref<PokemonMap>({})
  const pokemonList = computed(() => Object.values(pokemonMap.value))

  // 初始化宝可梦数据
  const initData = () => {
    const pokemonData = defaultConfig.pokémon as Pokemon[]
    pokemonMap.value = pokemonData.reduce((acc, pokemon) => {
      acc[pokemon.id] = pokemon
      return acc
    }, {} as PokemonMap)

    // 同步到全局对象
    GlobalPokemonData.data = { ...pokemonMap.value }
    GlobalPokemonData.dataArr = pokemonData
    GlobalPokemonData.length = pokemonData.length
    console.log('宝可梦数据初始化完成', pokemonMap.value)
  }

  // 根据id获取宝可梦数据
  const getPokemonById = (id: string): Pokemon | undefined => {
    return pokemonMap.value[id]
  }

  return {
    pokemonMap,
    pokemonList,
    initData,
    getPokemonById,
  }
})
